import React, { Component, Fragment } from 'react';
import styles from './css/TodoList.module.css';
import TodoItem from './TodoItem';

class TodoList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: '',
      list: ['吃饭', '睡觉', '思考人生'],
    };
  }

  getTodoItem = () => {
    return this.state.list.map((item, index) => {
      return (
        <TodoItem
          key={index}
          item={item}
          index={index}
          handleItemDelete={this.handleItemDelete}
        />
      );
    });
  };

  render() {
    return (
      <div className={styles.todoList}>
        <div className={styles.top}>
          <input
            type="text"
            value={this.state.inputValue}
            onChange={this.handleInputChange}
            ref="input_ref"
          />
          <button onClick={this.handleItemAdd}>添加</button>
        </div>
        <ul className={styles.itemList}>{this.getTodoItem()}</ul>
      </div>
    );
  }

  componentDidMount() {
    this.refs.input_ref.focus(); // ? 过时了，暂时用一用
  }

  handleInputChange = (e) => {
    console.log(e.target.value);
    this.setState({
      inputValue: e.target.value,
    });
  };

  handleItemAdd = () => {
    if (!this.state.inputValue.trim()) {
      alert('输入不能为空！');
    } else {
      this.setState({
        list: [...this.state.list, this.state.inputValue],
        inputValue: '',
      });
    }

    this.refs.input_ref.focus(); // ? 过时了，暂时用一用
  };

  handleItemDelete = (index) => {
    console.log(index);
    let list = [...this.state.list];
    list.splice(index, 1);
    this.setState({
      list,
    });
  };
}

export default TodoList;
